<template>
  <view class="company-container">
    <view class="form-content">
      <up-form
        labelPosition="left"
        :model="boilerForm"
        ref="boilerFormRef"
        labelWidth="100px"
      >
        <view class="form-card">
          <view class="collapse-custom-title flex align-item-center">
            <view class="line"></view>设备信息
            <view class="ml-20" v-if="boilerForm.updateType">
              <up-tag size="mini" :text="boilerForm.updateType" plain plainFill>
              </up-tag>
            </view>
          </view>
          <view
            class="checkStatus"
            v-if="boilerForm.checkStatus"
			@click="openCheckStatus"
            :class="{ warnColor: boilerForm.checkStatus == '审核不通过' }"
          >
            {{ boilerForm.checkStatus }}
          </view>

          <view class="collapse-item-content">
            <up-form-item label="锅炉编号" prop="code" borderBottom required>
              <up-input
                v-model="boilerForm.code"
                placeholder="请输入编码"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item
              label="燃料类型"
              prop="fuelType"
              borderBottom
              @click="openPicker('fuelType', '1865031771868000002')"
            >
              <up-input
                v-model="boilerForm.fuelType"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择燃烧类型"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>

            <up-form-item
              label="锅炉类型"
              prop="mediaType"
              borderBottom
              @click="openPicker('mediaType', '1865031771868000003')"
            >
              <up-input
                v-model="boilerForm.mediaType"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择锅炉类型"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="设备品牌" prop="boilerBrand" borderBottom>
              <up-input
                v-model="boilerForm.boilerBrand"
                placeholder="请输入设备品牌"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item label="设备型号" prop="boilerNameplate" borderBottom>
              <up-input
                v-model="boilerForm.boilerNameplate"
                placeholder="请输入设备型号"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item label="额定功率" prop="boilerPower" borderBottom>
              <up-input
                type="digit"
                v-model="boilerForm.boilerPower"
                placeholder="请输入额定功率"
                border="none"
              ></up-input>
            </up-form-item>

            <up-form-item
              label="额定单位"
              prop="boilerPowerUnit"
              borderBottom
              @click="openPicker('boilerPowerUnit', '1865031771868000005')"
            >
              <up-input
                v-model="boilerForm.boilerPowerUnit"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择额定单位"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>

            <up-form-item
              label="运行状态"
              prop="runingState"
              borderBottom
              @click="openPicker('runingState', '1865031771868000001')"
            >
              <up-input
                v-model="boilerForm.runingState"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择运行状态"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>

            <up-form-item
              label="制造日期"
              prop="boilerProductionDt"
              borderBottom
              @click="openDatePicker('boilerProductionDt')"
            >
              <up-input
                v-model="boilerForm.boilerProductionDt"
                disabled
                disabledColor="#ffffff"
                placeholder="请选择制造日期"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
            <up-form-item label="采暖季运行" prop="heatingSeason" borderBottom>
              <up-radio-group
                v-model="boilerForm.heatingSeason"
                placement="row"
              >
                <up-radio label="是" name="是"></up-radio>
                <up-radio label="否" name="否"></up-radio>
              </up-radio-group>
            </up-form-item>

            <up-form-item label="铭牌照片" prop="boilerNameplateImage">
              <up-upload
                :fileList="boilerForm.boilerNameplateImage"
                @afterRead="afterRead"
                @delete="deletePic"
                :previewFullImage="true"
                name="1"
                multiple
                :maxCount="2"
              ></up-upload>
            </up-form-item>
          </view>
        </view>
        <view class="form-card mt-20">
          <view class="collapse-custom-title">
            <view class="line"></view>最近一次改造情况
          </view>
          <view class="collapse-item-content">
            <up-form-item
              label="低碳改造时间"
              prop="nitrogenTransformDt"
              borderBottom
              @click="openDatePicker('nitrogenTransformDt')"
            >
              <up-input
                v-model="boilerForm.nitrogenTransformDt"
                placeholder="请选择改造时间"
                disabled
                disabled-color="#ffffff"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
            <up-form-item
              label="低碳改造方式"
              prop="nitrogenTransformMethod"
              @click="
                openPicker('nitrogenTransformMethod', '1865031771868000016')
              "
            >
              <up-input
                v-model="boilerForm.nitrogenTransformMethod"
                placeholder="请输入低碳改造方式"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
          </view>
        </view>

        <view class="form-card mt-20">
          <view class="collapse-custom-title">
            <view class="line"></view>燃烧器信息
          </view>
          <view class="collapse-item-content">
            <up-form-item label="品牌" prop="combustorBrand" borderBottom>
              <up-input
                v-model="boilerForm.combustorBrand"
                placeholder="请输入品牌"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item label="型号" prop="combustorModelNumber" borderBottom>
              <up-input
                v-model="boilerForm.combustorModelNumber"
                placeholder="请输入型号"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item
              label="制造时间"
              prop="combustorProductionDt"
              borderBottom
              @click="openDatePicker('combustorProductionDt')"
            >
              <up-input
                v-model="boilerForm.combustorProductionDt"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择制造时间"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
            <up-form-item
              label="低氮燃烧技术类型"
              prop="nitrogenBurnType"
              borderBottom
              @click="openPicker('nitrogenBurnType', '1865031771868000007')"
            >
              <up-input
                v-model="boilerForm.nitrogenBurnType"
                placeholder="请选择燃烧技术类型"
                disabled
                disabled-color="#ffffff"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="燃烧器照片" prop="combustorNameplateImage">
              <up-upload
                :fileList="boilerForm.combustorNameplateImage"
                @afterRead="afterReadRSq"
                @delete="deleteRSqPic"
                :previewFullImage="true"
                name="1"
                multiple
                :maxCount="3"
              ></up-upload>
            </up-form-item>
          </view>
        </view>
        <view class="form-card mt-20">
          <view class="collapse-custom-title">
            <view class="line"></view>排放情况
          </view>

          <view class="collapse-item-content">
            <up-form-item label="烟囱高度" prop="chimneyHeight" borderBottom>
              <up-input
                type="digit"
                v-model="boilerForm.chimneyHeight"
                placeholder="请输入烟囱高度"
                border="none"
              ></up-input>
            </up-form-item>
            <up-form-item
              label="排烟方式"
              prop="smokeWay"
              borderBottom
              @click="openPicker('smokeWay', '1865031771868000008')"
            >
              <up-input
                v-model="boilerForm.smokeWay"
                disabled
                disabled-color="#ffffff"
                placeholder="请选择排烟方式"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
            <up-form-item
              label="NOx限值"
              prop="noLimitValue"
              borderBottom
              @click="openPicker('noLimitValue', '1865031771868000015')"
            >
              <up-input
                type="digit"
                disabled
                disabled-color="#fff"
                v-model="boilerForm.noLimitValue"
                placeholder="请输入氮氧化物限值"
                border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-down"></up-icon>
              </template>
            </up-form-item>
            <up-form-item
              label="是否安装氮氧化物在线监测"
              prop="noCheckDevice"
              borderBottom
            >
              <up-radio-group
                v-model="boilerForm.noCheckDevice"
                placement="row"
              >
                <up-radio label="是" name="是"></up-radio>
                <up-radio label="否" name="否"></up-radio>
              </up-radio-group>
            </up-form-item>
            <up-form-item label="在线检测是否联网" prop="noCheckOnline">
              <up-radio-group
                v-model="boilerForm.noCheckOnline"
                placement="row"
              >
                <up-radio label="是" name="是"></up-radio>
                <up-radio label="否" name="否"></up-radio>
              </up-radio-group>
            </up-form-item>
          </view>
        </view>
      </up-form>
    </view>
    <!-- 公用picker -->
    <up-picker
      :show="pickerShow"
      :columns="[pickerData]"
      :defaultIndex="pickerIndex"
      @confirm="pickerConfirm"
      @cancel="pickerCancel"
    ></up-picker>

    <up-datetime-picker
      :show="datePickerShow"
      v-model="defaultDate"
      mode="year-month"
      @confirm="onDateConfirm"
      @cancel="datePickerShow = false"
    ></up-datetime-picker>

    <view class="bottom-btn">
      <up-button
        type="primary"
        color="#246eff"
        shape="circle"
        @click="handleSubmit"
        >保存</up-button
      >
    </view>
  </view>
</template>

<script>
import {
  getBoilerInfo,
  addOrEditBoiler,
  getDictList,
  uploadImg,
  deleteImg,
} from '../../api/company';
import { formatDate, formatToMonth } from '../../utils/format';

export default {
  data() {
    return {
      dialogType: 'add',
      pickerShow: false,
      pickerData: [],
      pickerIndex: [],
      propertyName: '', //属性名
      datePickerShow: false,
      defaultDate: Date.now(),
      boilerForm: {
        checkStatus: '',
        companyId: '',
        stationId: '',
        code: '',
        fuelType: '', // 燃料类型
        mediaType: '', //锅炉介质类型
        boilerBrand: '', //设备品牌
        boilerNameplate: '', //设备型号
        boilerNameplateImage: [],
        boilerPower: null, //额定功率（出力)
        boilerPowerUnit: '', //功率单位
        boilerProductionDt: null, //锅炉制造日期
        heatingSeason: '', //是否采暖季运行
        runingState: '', //运行状态
        nitrogenTransformDt: null, //最近低氮改造时间
        nitrogenTransformMethod: '', //低氮改造方式
        combustorBrand: '', // 燃烧器品牌
        combustorNameplateImage: [], // 燃烧器铭牌照片
        combustorModelNumber: '', // 燃烧器型号
        combustorProductionDt: null, //燃烧器制造日期
        nitrogenBurnType: '', //低氮燃烧技术类型
        chimneyHeight: null, //烟囱高度
        smokeWay: '', // 排烟方式
        noLimitValue: '', //氮氧化物限值
        noCheckDevice: '', //是否按照氮氧化物在线检测
        noCheckOnline: '', //在线检测是否联网
        permitBoilerNumber: '', //排污许可证锅炉编号
        permitDischargeNumber: '', //排污许可证排放口编号
        permitTreatmentNumber: '', //排污许可证治理设施编号
        remark: '', //备注
        sort: 1, //排序
        updateType: '',
      },
      rules: {
        code: [
          {
            required: true,
            message: '请填写编号',
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  onLoad(options) {
    this.initData(options);
  },
  mounted() {
    this.$refs.boilerFormRef.setRules(this.rules);
  },
  methods: {
    async initData(options) {
      const { type, boilerInfo } = options;
      this.dialogType = type;
      uni.setNavigationBarTitle({
        title: type == 'add' ? '添加锅炉' : '锅炉详情',
      });
      let boilerObj = JSON.parse(decodeURIComponent(boilerInfo));
      this.boilerForm.companyId = boilerObj.companyId;
      this.boilerForm.stationId = boilerObj.stationId;

      if (type == 'add') {
        this.$refs.boilerFormRef.resetFields();
      } else {
        const data = await getBoilerInfo(boilerObj.id, { checkTag: 1 });
        const {
          boilerProductionDt,
          nitrogenTransformDt,
          combustorProductionDt,
          boilerNameplateImage = [],
          combustorNameplateImage = [],
        } = data;
        this.boilerForm = {
          ...data,
        };
        this.boilerForm.boilerNameplateImage =
          boilerNameplateImage === null ? [] : boilerNameplateImage;
        this.boilerForm.combustorNameplateImage =
          combustorNameplateImage === null ? [] : combustorNameplateImage;
        this.boilerForm.boilerProductionDt = boilerProductionDt
          ? formatToMonth(boilerProductionDt)
          : '';
        this.boilerForm.nitrogenTransformDt = nitrogenTransformDt
          ? formatToMonth(nitrogenTransformDt)
          : '';
        this.boilerForm.combustorProductionDt = combustorProductionDt
          ? formatToMonth(combustorProductionDt)
          : '';
      }
    },
	/**点击审核状态**/
	openCheckStatus(){
		const title=this.boilerForm.checkOpinion||''
		if(title){
			uni.showModal({
				title:'审核意见',
				content:title
			})
		}
		
	},
    handleOpen(arr) {},

    /**打开picker */
    async openPicker(property, id) {
      this.propertyName = property;
      const list = await getDictList(id);
      this.pickerData = list || [];
      if (this.boilerForm[property]) {
        const value = this.boilerForm[property];
        const idx = this.pickerData.findIndex((item) => item === value);
        this.pickerIndex = [idx];
      } else {
        this.pickerIndex = [0];
      }
      this.pickerShow = true;
    },
    /*下拉确认*/
    pickerConfirm(e) {
      const name = this.propertyName;
      this.boilerForm[name] = e.value[0];
      this.pickerShow = false;
      this.$refs.boilerFormRef.validateField(name);
    },
    /*下拉取消*/
    pickerCancel(e) {
      this.pickerIndex = [0];
      this.pickerShow = false;
    },
    /**打开时间下拉**/
    openDatePicker(name) {
      this.propertyName = name;
      const dateVal = this.boilerForm[name];
      this.datePickerShow = true;
      this.defaultDate = dateVal ? new Date(dateVal).getTime() : Date.now();
    },
    onDateConfirm(e) {
      const name = this.propertyName;
      this.boilerForm[name] = formatToMonth(e.value);
      this.datePickerShow = false;
    },
    /**上传图片**/
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this.boilerForm.boilerNameplateImage.length;
      lists.forEach((item) => {
        this.boilerForm.boilerNameplateImage.push({
          ...item,
          status: 'uploading',
          message: '上传中',
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await uploadImg(lists[i].url, {
          stationId: this.boilerForm.stationId,
        });
        // const { userName, userId, fileName, filePath, time, url } = result;
        let item = this.boilerForm.boilerNameplateImage[fileListLen];
        this.boilerForm.boilerNameplateImage.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: 'success',
            message: '',
            ...result,
          })
        );
        fileListLen++;
      }
      this.$refs.boilerFormRef.validateField('boilerNameplateImage');
    },

    /**删除图片**/
    async deletePic(event) {
      const { index, file } = event;
      const res = await deleteImg({
        filePath: file.url,
      });
      uni.showToast({
        title: '删除照片成功！',
      });
      this.boilerForm.boilerNameplateImage.splice(index, 1);
    },
    /**燃烧器图片上传**/
    async afterReadRSq(event) {
      let fileList = [].concat(event.file);
      let fileImgLen = this.boilerForm.combustorNameplateImage.length;
      fileList.forEach((item) => {
        this.boilerForm.combustorNameplateImage.push({
          ...item,
          status: 'uploading',
          message: '上传中',
        });
      });

      for (let i = 0; i < fileList.length; i++) {
        const result = await uploadImg(fileList[i].url, {
          stationId: this.boilerForm.stationId,
        });

        let item = this.boilerForm.combustorNameplateImage[fileImgLen];
        this.boilerForm.combustorNameplateImage.splice(
          fileImgLen,
          1,
          Object.assign(item, {
            status: 'success',
            message: '',
            ...result,
          })
        );
        fileImgLen++;
      }
    },
    /**删除燃烧器图片**/
    async deleteRSqPic(event) {
      const { index, file } = event;
      const res = await deleteImg({
        filePath: file.url,
      });
      uni.showToast({
        title: '删除照片成功！',
      });
      this.boilerForm.combustorNameplateImage.splice(index, 1);
    },
    handleSubmit() {
      this.$refs.boilerFormRef
        .validate()
        .then((valid) => {
          if (valid) {
            const {
              boilerProductionDt,
              nitrogenTransformDt,
              combustorProductionDt,
              boilerPower,
              noLimitValue,
              chimneyHeight,
            } = this.boilerForm;
            const params = {
              ...this.boilerForm,
            };
            params.boilerProductionDt = boilerProductionDt
              ? `${boilerProductionDt}-01`
              : null;
            params.nitrogenTransformDt = nitrogenTransformDt
              ? `${nitrogenTransformDt}-01`
              : null;
            params.combustorProductionDt = combustorProductionDt
              ? `${combustorProductionDt}-01`
              : null;
            params.boilerPower = Number(boilerPower);
            params.noLimitValue = Number(noLimitValue);
            params.chimneyHeight = Number(chimneyHeight);

            addOrEditBoiler(params).then((res) => {
              uni.$u.toast(this.dialogType == 'add' ? '添加成功' : '保存成功');
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index',
                });
              }, 1000);
            });
          } else {
            uni.$u.toast('校验失败');
          }
        })
        .catch(() => {
          // 处理验证错误
          uni.$u.toast('校验失败');
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.company-container {
  width: 100%;
  min-height: 100vh;
  padding: 20rpx 20rpx 200rpx 20rpx;
  box-sizing: border-box;
  position: relative;
  background: #f8f8f8;
}

.form-content {
  width: 100%;
}

.form-card {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  position: relative;

  .collapse-custom-title {
    color: #333;
    font-size: 34rpx;
    font-weight: bold;
    margin-bottom: 20rpx;

    .line {
      width: 5px;
      height: 15px;
      border-radius: 10px;
      display: inline-block;
      margin-right: 20rpx;
      vertical-align: -2rpx;
      background-color: #0e8fe5;
    }
  }
  .checkStatus {
    position: absolute;
    right: 0;
    top: 0;
    padding: 12rpx 20rpx;
    background-color: #f60;
    font-size: 25rpx;
    color: #fff;
    font-weight: bold;
    border-radius: 4rpx 12rpx 4rpx 12rpx;
    &.warnColor {
      background-color: #f56c6c;
    }
  }

  .collapse-item-content {
    padding: 0 20rpx;
  }
}

.bottom-btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  padding: 40rpx 30rpx;
  left: 0;
  z-index: 100;
  box-sizing: border-box;
  background: #fff;
  border-top: 1px solid #f4f4f4;
}
</style>
